package com.usian.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.Result;
import com.usian.common.ResultCodeEnum;
import com.usian.dto.OrderDto;
import com.usian.entity.OrderDetails;
import com.usian.dto.OrderDto;
import com.usian.entity.Orders;
import com.usian.order.mapper.OrdersMapper;
import com.usian.order.service.IOrderDetailsService;
import com.usian.order.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.order.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-15
 */
@Service
public class  OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Override
    public Result<Orders> getOrderByUserId(Integer userId) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, userId);
        wrapper.eq(Orders::getOrderStatus, "已归还");
        wrapper.orderByDesc(Orders::getUpdatedAt);
        List<Orders> list = list(wrapper);
        if (list.isEmpty()) {
            return Result.build(null, ResultCodeEnum.ORDERS_NOT_EXISTS);
        }
        Orders order = list.get(0);
        return Result.build(order, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<Orders> findAllBooked(Integer userId) {
        // 优化：使用 MyBatis-Plus 的 LambdaQueryWrapper 进行查询，根据订单创建时间倒序，且订单状态为已预定
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<Orders>();
        wrapper.eq(Orders::getUserId, userId);
        wrapper.eq(Orders::getOrderStatus, "已预定");  // 筛选订单状态为已预定
        wrapper.orderByDesc(Orders::getCreatedAt);  // 根据订单创建时间倒序排序
        wrapper.last("limit 1");// 只返回一条记录

        // 获取满足条件的最新订单信息
        Orders orders = getOne(wrapper);
//        if (orders==null){
//            LambdaQueryWrapper<Orders> wrapper1 = new LambdaQueryWrapper<Orders>();
//            wrapper1.eq(Orders::getUserId, userId);
//            wrapper1.eq(Orders::getOrderStatus, "已支付");  // 筛选订单状态为已预定
//            wrapper1.orderByDesc(Orders::getCreatedAt);  // 根据订单创建时间倒序排序
//            wrapper1.last("limit 1");// 只返回一条记录
//            orders = getOne(wrapper1);
//        }

        return Result.build(orders, ResultCodeEnum.SUCCESS);
    }

    @Override
    public List<Orders> findOrderHistory(Integer userId) {
        //查询用户已归还的订单
        LambdaQueryWrapper<Orders> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Orders::getUserId, userId);
        wrapper.eq(Orders::getOrderStatus, "已归还");
        List<Orders> orders = list(wrapper);
        return orders;
    }

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public Orders selectByOrderNo(String orderId) {
        //查询订单信息
        return ordersMapper.selectByOrderNo(orderId);
    }

    @Override
    public Result<Orders> findAllzhifu(Integer userId) {
        // 优化：使用 MyBatis-Plus 的 LambdaQueryWrapper 进行查询，根据订单创建时间倒序，且订单状态为已预定
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<Orders>();
        wrapper.eq(Orders::getUserId, userId);
        wrapper.eq(Orders::getOrderStatus, "已支付");  // 筛选订单状态为已预定
        wrapper.orderByDesc(Orders::getCreatedAt);  // 根据订单创建时间倒序排序
        wrapper.last("limit 1");// 只返回一条记录

        // 获取满足条件的最新订单信息
        Orders orders = getOne(wrapper);

        return Result.build(orders, ResultCodeEnum.SUCCESS);
    }

    @Autowired
    private IOrderDetailsService orderDetailsService;

    //添加  orders  order_details
    @Override
    public Result addOrders(OrderDto orderDto) {

        try {
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.eq(Orders::getUserId, orderDto.getUserId());
            ordersLambdaQueryWrapper.eq(Orders::getOrderStatus, "已预定");
            List<Orders> list = list(ordersLambdaQueryWrapper);
            if (!list.isEmpty()) {
                return Result.build(false, ResultCodeEnum.ORDER_EXISTS);
            }
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper1.eq(Orders::getUserId, orderDto.getUserId());
            ordersLambdaQueryWrapper1.eq(Orders::getOrderStatus, "已支付");
            List<Orders> list1 = list(ordersLambdaQueryWrapper1);
            if (!list1.isEmpty()) {
                return Result.build(false, ResultCodeEnum.ORDER_EXISTS);
            }
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();

            // 创建一个新的订单对象
            Orders orders = new Orders();
            // 设置订单的用户ID
            orders.setUserId(orderDto.getUserId());
            // 设置订单的车辆ID
            orders.setCarId(orderDto.getCarId());
            // 设置订单状态为"已预定"
            orders.setOrderStatus("已预定");
            // 设置订单的开始时间
            orders.setStartTime(orderDto.getStartTime());
            // 设置订单的结束时间
            orders.setEndTime(orderDto.getEndTime());
            // 设置订单的总价格
            orders.setTotalPrice(orderDto.getTotalPrice());
            // 设置订单的创建时间
            orders.setCreatedAt(now);
            // 设置订单的更新时间
            orders.setUpdatedAt(now);
            // 保存订单信息到数据库
            save(orders);

            // 创建一个新的订单详情对象
            OrderDetails orderDetails = new OrderDetails();
            // 设置订单详情的订单ID
            orderDetails.setOrderId(orders.getOrderId());
            // 设置订单详情的车辆ID
            orderDetails.setCarId(orders.getCarId());
            // 设置订单详情的租赁开始日期
            orderDetails.setRentalStartDate(orderDto.getStartTime().toLocalDate()); // 根据业务逻辑调整
            // 设置订单详情的租赁结束日期
            orderDetails.setRentalEndDate(orderDto.getEndTime().toLocalDate()); // 根据业务逻辑调整
            // 设置订单详情的取车地点
            orderDetails.setPickupLocation(orderDto.getPickupLocation());
            // 设置订单详情的总费用
            orderDetails.setTotalCost(orders.getTotalPrice());
            // 保存订单详情信息到数据库
            orderDetailsService.save(orderDetails);

            // 如果以上操作成功，返回true
            return Result.build(orders.getOrderId(), ResultCodeEnum.SUCCESS);
        } catch (Exception e) {
            // 如果发生异常，打印错误信息
            System.out.println("添加订单失败");
            // 如果以上操作失败，返回false
            return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
        }

    }


}
